#include "../include/intern.h"
#include "../include/environ.h"
#include "../include/history.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/* Fonction cd */
void fct_cd(int argc, char* argv[]) {
    if(argc == 2) {
      chdir(argv[1]);
      char buffer[256];
      getcwd(buffer, 256);
      set_environ("PWD", buffer);
    } else if(argc == 1) {
      set_environ("PWD", get_environ("HOME"));
      if(-1 == chdir(get_environ("HOME"))){
          puts("Erreur chdir");
      }
    } else {
        puts("Erreur usage : cd <path> ou  cd");
    }
}

/* Fonction echo */
void fct_echo(int argc, char* argv[]) {
    int i = 1;
    while(i < argc) {
        printf("%s", argv[i++]);
        printf(" ");
    }
    printf("\n");
}

/* Commande exit */
void fct_exit (int argc, char* arg[]) {
    exit(EXIT_SUCCESS);
}

/* Commande PWD */
void fct_pwd (int argc, char* arg[]) {
    printf("%s\n", get_environ("PWD"));
}

/* Commande read */
void fct_read(int argc, char* argv[]) {
   if(argc != 2)
     puts("Erreur usage : read <variable>");
   printf("%s: ", argv[1]);
   fflush(stdout);
   char input[300];
   char* tmp = fgets(input, 300, stdin);
   if(tmp)
    input[strlen(input)-1] = '\0';
   set_environ(argv[1], input);
}

/* Commande Set */
void fct_set(int argc, char* argv[]) {
   if(argc == 1) // Affichage des variables d'environnement
      print_environ(stdout);
   else if(argc == 3) {
      set_environ(argv[1], argv[2]);
   } else {
      puts("Erreur usage : set ou set var val");
   }
}

/* Commande history */
void fct_history(int argc, char* argv[]) {
   if(argc != 1)
     puts("Erreur usage: history");
   print_history(stdout);    
}

/* Fonction pour determiner a quelle commande correspond name */
internal_cmd find_internal(char *name) {
    if(strcmp("cd", name) == 0 || strcmp("chdir", name) == 0) {
        return fct_cd;
    } else if(strcmp("echo", name) == 0) {
        return fct_echo;
    } else if(strcmp("exit", name) == 0) {
        return fct_exit;
    } else if(strcmp("pwd", name) == 0) {
        return fct_pwd;
    } else if(strcmp("read", name) == 0) {
        return fct_read;
    } else if(strcmp("set", name) == 0) {
        return fct_set;
    } else if(strcmp("history", name) == 0) {
        return fct_history;
    } else
        return NULL;
}


